package com.ncst.backend.service.impl;

import com.ncst.backend.domain.vo.DispenseItemVo;
import com.ncst.backend.domain.vo.DispensePatientVo;
import com.ncst.backend.mapper.DispenseMapper;

import com.ncst.backend.service.DispenseService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Collections;

@Service
@RequiredArgsConstructor
public class DispenseServiceImpl implements DispenseService {

    private final DispenseMapper dispenseMapper;
    //private final DispensePrescriptionMapper dispensePrescriptionMapper;
    //private final DispenseRegisterMapper dispenseRegisterMapper;

    @Override
    public DispensePatientVo getPatientByCaseNumber(String caseNumber) {
        return dispenseMapper.selectPatientByCaseNumber(caseNumber);
    }

    @Override
    public List<DispenseItemVo> listWaitDispense(String caseNumber) {
        if (caseNumber == null || caseNumber.trim().isEmpty()) {
            throw new IllegalArgumentException("病历号不能为空");
        }
        DispensePatientVo patient = dispenseMapper.selectPatientByCaseNumber(caseNumber);
        if (patient == null || patient.getId() == null) {
            return Collections.emptyList();
        }
        return dispenseMapper.selectWaitDispenseList(patient.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dispense(List<Integer> ids) {
        // 1. 查询待发药明细
//        List<DispenseItemVo> items = dispenseMapper.selectWaitDispenseListByIds(ids);
//        if (items.size() != ids.size()) {
//            throw new RuntimeException("存在非法或已发药记录");
//        }

//        // 2. 扣库存
//        for (DispenseItemVo item : items) {
//            int cnt = dispenseMapper.decreaseStock(item.getDrugId(), item.getQuantity());
//            if (cnt == 0) {
//                throw new RuntimeException("药品【" + item.getProjectName() + "】库存不足");
//            }
//        }

        // 3. 批量改发药状态
        int rows = dispenseMapper.updateToDispensed(ids);
        if (rows == 0) {
            throw new RuntimeException("发药状态更新失败");
        }
    }
}
